﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
namespace URLShorterService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://developerpath.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        private string _connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnection"].ToString();
        public string logPath = System.Configuration.ConfigurationManager.AppSettings["logPath"].ToString();
        public static string _lower_case = "abcdefgijkmnopqrstwxyz";
        public static string _upper_case = "ABCDEFGHJKLMNPQRSTWXYZ";
        public static string _number_case = "0123456789";
        [WebMethod]
        public string CreatURL(string originalURL)
        {
            string _smallurl = "";
            while (true)
            {
                _smallurl = GenerateURL();
                if (CheckExists(_smallurl) == false)
                {
                    StoreURL(originalURL,_smallurl);
                    return System.Configuration.ConfigurationManager.AppSettings["UrlDomain"].ToString() + _smallurl;
                }
            }
        }
        public bool CheckExists(string smallURL)
        {
            bool _Result = false;
            try
            {
                SqlConnection connection = new SqlConnection(_connectionstring);
                SqlCommand com = new SqlCommand();
                connection.Open();
                com.Connection = connection;
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "spr_URLShort_CheckExists";
                com.Parameters.AddWithValue("@short_URL", smallURL);
                com.ExecuteReader();
                connection.Close();
                SqlDataAdapter adp = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    _Result = true;
                }
                return _Result;
            }
            catch (Exception ex) 
            {
                CatchThatException.logException(ex, logPath);
                _Result = false;
                return _Result;
            }
        }
        private string GenerateURL()
        {
            string _smallurl = "";
            Random _URLRandomizer = new Random();
            for (int i = 0; i < 3; i++)
            {
                if (_URLRandomizer.Next(0, 2) == 1)
                {
                    _smallurl += _lower_case.Substring(_URLRandomizer.Next(0, 21), 1);
                    _smallurl += _upper_case.Substring(_URLRandomizer.Next(0, 21), 1);
                }
                else
                {
                    _smallurl += _upper_case.Substring(_URLRandomizer.Next(0, 21), 1);
                    _smallurl += _lower_case.Substring(_URLRandomizer.Next(0, 21), 1);
                }
                //_smallurl += _number_case.Substring(_URLRandomizer.Next(0, 9), 1);
            }
            return _smallurl;
        }
        protected int StoreURL(string URL,string shortUrl)
        {
            try
            {
                SqlConnection connection = new SqlConnection(_connectionstring);
                SqlCommand com = new SqlCommand();
                connection.Open();
                com.Connection = connection;
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "spr_URLShort_NewURL";
                com.Parameters.AddWithValue("@URL_longURL", URL);
                com.Parameters.AddWithValue("@URL_shortURL", shortUrl);
                com.Parameters.AddWithValue("@URL_Date", DateTime.Now);
                com.ExecuteNonQuery();
                connection.Close();
            }
            catch (Exception ex)
            {
                CatchThatException.logException(ex, logPath);
                return -1;
            }
            return 0;
        }
    }
}